<?php

namespace app\store\controller\market;

use app\store\controller\Controller;
use app\store\model\Coupon as CouponModel;
use app\store\model\Goods as GoodsModel;
use app\store\model\UserCoupon as UserCouponModel;
use app\store\model\User as UserModel;
use app\store\model\Category as CategoryModel;
use think\Session;

/**
 * 优惠券管理
 * Class Coupon
 * @package app\store\controller\market
 */
class Coupon extends Controller
{
    /* @var CouponModel $model */
    private $model;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CouponModel;
    }

    /**
     * 优惠券列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = $this->model->getList();
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加优惠券
     * @return array|mixed
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            // 获取全部商品列表
            $model = new GoodsModel;
            // 商品列表获取条件
            $param = [
                'status' => 10,         // 商品状态
                'category_id' => 0,     // 分类id
                'sortType' => 'all',    // 排序类型
                'sortPrice' => false,   // 价格排序 高低
                'listRows' => 500000,
                'goods_type' => 0,     //服务类商品
            ];
            $goods_list = $model->getList($param);
            $category = CategoryModel::getCacheTree();
            return $this->fetch('add',compact('goods_list','category'));
        }
        // 新增记录
        if ($this->model->add($this->postData('coupon'))) {
            $coupon_id = $this->model->getLastInsID();
            $this->xcxqrcode($coupon_id);
            //指派用户
            $data = $this->postData('coupon');
            if($data['is_daijin']==0 && $data['user_id'] > 0){
                $coupon['user_id'] = $data['user_id'];
                $coupon['coupon_id'] = $coupon_id;
                $coupon['type'] = $data['type'];
                $coupon['goods_ids'] = $data['goods_ids'];
                $coupon['category_id'] = $data['category_id'];
                $coupon['name'] = $data['name'];
                $coupon['color'] = $data['color'];
                $coupon['coupon_type'] = $data['coupon_type'];
                $coupon['reduce_price'] = $data['reduce_price'];
                $coupon['discount'] = $data['discount'];
                $coupon['min_price'] = $data['min_price'];
                $coupon['expire_type'] = $data['expire_type'];
                $coupon['expire_day'] = $data['expire_day'];
                if ($coupon['expire_type'] == 10) {//领取生效
                    $coupon['start_time'] = time();
                    $coupon['end_time'] = time() + 86400 * $coupon['expire_day'];
                } else {
                    $coupon['start_time'] = $data['start_time'];
                    $coupon['end_time'] = $data['end_time'];
                }
                $coupon['create_time'] = time();
                $coupon['update_time'] = time();
                $user_coupon = new UserCouponModel;
                $user_coupon->add($coupon);
            }
            return $this->renderSuccess('添加成功', url('market.coupon/index'));
        }
        return $this->renderError($this->model->getError() ?: '添加失败');
    }

    /**
     * 更新优惠券
     * @param $coupon_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($coupon_id)
    {
        // 优惠券详情
        $model = CouponModel::detail($coupon_id);
        if(!$model['xcx_qrcode']){
            $this->xcxqrcode($coupon_id);
        }
        $user = UserModel::detail($model['user_id']);
        $model['nickname'] = $user['nickName'];
        $model['avatar'] = $user['avatarUrl'];
        $coupon_userid = $model['user_id'];
        if (!$this->request->isAjax()) {
            // 商品列表获取条件
            $param = [
                'status' => 10,         // 商品状态
                'category_id' => 0,     // 分类id
                'sortType' => 'all',    // 排序类型
                'sortPrice' => false,   // 价格排序 高低
                'listRows' => 500000,
                'goods_type' => 0,     //服务类商品
            ];
            $good_model = new GoodsModel;
            $goods_list = $good_model->getList($param);

            $category = CategoryModel::getCacheTree();

            return $this->fetch('edit', compact('model','goods_list','category'));
        }

        // 更新记录
        if ($model->edit($this->postData('coupon'))) {
            //指派用户
            $data = $this->postData('coupon');
            if($data['is_daijin']==0 && $data['user_id'] > 0 && $data['user_id'] != $coupon_userid){
                $coupon['user_id'] = $data['user_id'];
                $coupon['coupon_id'] = $coupon_id;
                $coupon['type'] = $data['type'];
                $coupon['goods_ids'] = $data['goods_ids'];
                $coupon['category_id'] = $data['category_id'];
                $coupon['name'] = $data['name'];
                $coupon['color'] = $data['color'];
                $coupon['coupon_type'] = $data['coupon_type'];
                $coupon['reduce_price'] = $data['reduce_price'];
                $coupon['discount'] = $data['discount'];
                $coupon['min_price'] = $data['min_price'];
                $coupon['expire_type'] = $data['expire_type'];
                $coupon['expire_day'] = $data['expire_day'];
                if($coupon['expire_type'] == 10){//领取生效
                    $coupon['start_time'] = time();
                    $coupon['end_time'] = time() + 86400*$coupon['expire_day'];
                }else{
                    $coupon['start_time'] = $data['start_time'];
                    $coupon['end_time'] = $data['end_time'];
                }

                $coupon['create_time'] = time();
                $coupon['update_time'] = time();

                $user_coupon = new UserCouponModel;
                $user_coupon->add($coupon);
            }

            return $this->renderSuccess('更新成功', url('market.coupon/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除优惠券
     * @param $coupon_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function delete($coupon_id)
    {
        // 优惠券详情
        $model = CouponModel::detail($coupon_id);
        // 更新记录
        if ($model->setDelete()) {
            return $this->renderSuccess('删除成功', url('market.coupon/index'));
        }
        return $this->renderError($model->getError() ?: '删除成功');
    }

    /**
     * 领取记录
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function receive()
    {
        $model = new UserCouponModel;
        $list = $model->getList();
        return $this->fetch('receive', compact('list'));
    }

    function xcxqrcode($id)
    {
        //配置APPID、APPSECRET
        $APPID = "wxfc449efa209ab07e";
        $APPSECRET =  "a46a7f1590681d668f9b175b0cfc9923";
//获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

//缓存access_token
        Session::set('access_token','');
        Session::set('expires_in',0);


        $ACCESS_TOKEN = "";
        if(! Session::get('access_token') || (Session::get('expires_in')) && time() > Session::get('expires_in'))
        {

            $json = $this->httpRequest( $access_token );
            $json = json_decode($json,true);
            // var_dump($json);
            Session::set('access_token',$json['access_token']);
            Session::set('expires_in',time()+7200);
            $ACCESS_TOKEN = $json["access_token"];
        }
        else{

            $ACCESS_TOKEN =  Session::get('access_token');
        }

//构建请求二维码参数
//path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
//width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";

        $param = json_encode(array("path"=>"pages/coupon/coupon?id=$id","width"=> 150));

//POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");

        $model = new CouponModel();
        $model->where('coupon_id',$id)->update(['xcx_qrcode'=>"xcxqrcode/qrcode_".$id.".png"]);

//生成二维码
        file_put_contents("xcxqrcode/qrcode_".$id.".png", $result);
        //$base64_image ="data:image/jpeg;base64,".base64_encode( $result );

//把请求发送到微信服务器换取二维码
    }

    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
}